/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.diplomka.servicelayer.gamelogic.managerimpl;

import cz.fi.muni.diplomka.common.Squad;
import cz.muni.fi.diplomka.datalayer.dao.MarchingArmyDao;
import cz.muni.fi.diplomka.datalayer.daoimpl.MarchingArmyDaoImpl;
import cz.muni.fi.diplomka.datalayer.entity.MarchingArmyEntity;
import cz.muni.fi.diplomka.servicelayer.dto.MarchingArmy;
import cz.muni.fi.diplomka.servicelayer.gamelogic.manager.MarchingArmyManager;
import java.util.ArrayList;
import java.util.List;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;

/**
 *
 * @author Jakub Kutil
 */
public class MarchingArmyManagerImpl implements MarchingArmyManager {

    private MarchingArmyDao marchingArmyDao = new MarchingArmyDaoImpl();
    private CityUnitsManagerImpl cityUnitsManager = new CityUnitsManagerImpl();
    private Mapper mapper = new DozerBeanMapper();

    @Override
    public void createMarchingArmy(MarchingArmy marchingArmy) {
        if (marchingArmy == null) {
            throw new IllegalArgumentException("Marching Army can not be null");
        }
        marchingArmyDao.addMarchingArmy(mapper.map(marchingArmy, MarchingArmyEntity.class));
    }

    @Override
    public List<MarchingArmy> getAllMarchingArmiesOfCity(Long cityId) {
        if (cityId == null) {
            throw new IllegalArgumentException("City ID can not be null");
        }
        List<MarchingArmy> marchingArmies = new ArrayList<>();

        for (MarchingArmyEntity marchingArmyEntity : marchingArmyDao.getAllMarchingArmiesOfCity(cityId)) {
            marchingArmies.add(mapper.map(marchingArmyEntity, MarchingArmy.class));
        }

        return marchingArmies;
    }

    @Override
    public void deleteMarchingArmy(MarchingArmy marchingArmy) {
        if (marchingArmy == null) {
            throw new IllegalArgumentException("Marching army can not be null.");
        }
        for(Squad squad : marchingArmy.getArmy().getSquads()){
            cityUnitsManager.increaseUnitCount(marchingArmy.getCityIdFrom(),  squad.getUnit().getName(), (int) squad.getCount());
        }
        marchingArmyDao.deleteMarchingArmy(marchingArmy.getId());
    }

    @Override
    public List<MarchingArmy> getAllMarchingArmies() {

        List<MarchingArmy> marchingArmies = new ArrayList<>();

        for (MarchingArmyEntity marchingArmyEntity : marchingArmyDao.getAllMarchingArmies()) {
            marchingArmies.add(mapper.map(marchingArmyEntity, MarchingArmy.class));
        }

        return marchingArmies;
    }

    @Override
    public void editMarchingArmy(MarchingArmy marchingArmy) {
        if (marchingArmy == null) {
            throw new IllegalArgumentException("Marching Army can not be null");
        }
        marchingArmyDao.editMarchingArmy(mapper.map(marchingArmy, MarchingArmyEntity.class));
    }
}
